Skip to content

Keep a __namespace__ subclass's Python state while .NET holds it in a cycle - #176

Open
quantconnect-kronos[bot] wants to merge 3 commits into
masterfrom
kronos/bug-169-namespace-subclass-cycle-attributes
Open

quantconnect-kronos[bot] wants to merge 3 commits into
masterfrom
kronos/bug-169-namespace-subclass-cycle-attributes

Conversation

@quantconnect-kronos

@quantconnect-kronos quantconnect-kronos Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Closes #169

What changed and why

Python's cyclic GC can't see .NET's reference to an instance of a __namespace__ subclass. When the instance's last Python references formed a cycle, such as self.me = self, the GC treated the cycle as garbage and cleared it, the instance's __dict__ included, even while .NET still held the object. The GC clears the instance dict through the dict's own tp_clear, so the no-op ClassDerivedObject.tp_clear can't prevent it.

ClassDerivedObject now has a tp_finalize. The GC calls it on unreachable objects before it clears anything. Instead of letting the cycle be cleared, it hands the object to .NET, as tp_dealloc already does when the refcount reaches zero: the .NET object keeps one reference to the Python object, and the Python object holds the .NET object weakly. Because of that reference, the GC treats the object as resurrected and keeps the whole cycle intact. Then:

  • When the object returns to Python (ClassDerivedObject.ToPython), Python takes that reference back and holds the .NET object strongly again.
  • When .NET finalizes the object, PythonDerivedType.Finalize drops that reference, and Python frees the cycle as usual. tp_dealloc then hands the object to .NET as for any object, and .NET's next finalization frees it.
  • The GC calls tp_finalize only once per object, and it sets the object's finalized flag before the call. tp_finalize clears that flag so the GC calls it again the next time Python lets go of the object in a cycle. The flag is bit 0 of the GC header's _gc_prev (_PyGC_PREV_MASK_FINALIZED) on Python 3.8 to 3.14. On Python 3.7 it's bit 0 of gc_refs, the header's third word, and the header is padded to the platform's long double alignment, so the offset comes from sys.getsizeof([]) - [].__sizeof__(). Python 3.7 also calls tp_finalize only for types with Py_TPFLAGS_HAVE_FINALIZE, which CLR class types now set there. A direct __del__ call from Python arrives without the flag set, so it changes nothing.
  • Another object's __del__ in the same cycle can give Python the object back without going through ToPython, so Python may still reference the object when .NET finalizes it. The Python object holds the .NET object with a weak handle that tracks resurrection. When .NET finalizes a .NET object that holds the Python object's reference, the generated finalizer doesn't run the base type's finalizer: it queues the .NET object, and the queue keeps it alive until PythonDerivedType.Finalize handles it. That drops the reference and, if Python still references the object, the Python object holds the .NET object strongly again, as for any object Python holds. Either way, the .NET object is re-registered for finalization, so the base type's finalizer runs once, when .NET finalizes the object for good. The next time the GC finds such a cycle unreachable, tp_finalize lets it be freed instead of handing it to .NET again, unless the object was passed to .NET in between.
  • The .NET finalizer decides under a lock whether to defer, with tp_finalize and ToPython updating the same state, so ToPython taking the reference back before or after .NET finalized the object can't make the queued cleanup free a live Python object.

The fix also needed the wrapper (CLRObject) to survive while the Python object holds it weakly. Only that weak handle referenced the wrapper, so any .NET GC collected it while the .NET object was still alive. The object then came back from .NET with no wrapper: its .NET members raised TypeError: invalid object, and the next tp_finalize couldn't hand it to .NET. The weak handle now goes with a ConditionalWeakTable entry that keeps the wrapper alive exactly as long as its .NET object. This also fixes that error on master's existing path, for an object without a cycle that comes back from .NET after a .NET GC. All three handle swaps (tp_dealloc, tp_finalize, ToPython) share one helper, ReplaceGCHandle.

Known limits:

  • In a cycle of several __namespace__ objects where .NET holds only some of them, each object's Python state lasts as long as its own .NET object. The attributes of an object .NET doesn't hold stay reachable from the held ones, but its .NET members raise TypeError after .NET collects it. On master, the held objects lose all their attributes in this case.
  • Python weakrefs to an object in such a cycle are cleared when the GC finds the cycle, as for any garbage the GC resurrects.
  • A Python subclass that defines __del__ replaces tp_finalize and keeps master's behavior.
  • An object .NET held in a cycle is freed one .NET finalization later than on master, since its first finalization only drops Python's reference.

Tests

New tests in tests/test_subclass.py. They release objects by running Python's GC and .NET's GC, then passing Python objects to .NET to drain the queue of Python objects .NET released:

  • test_namespaced_subclass_held_by_net_keeps_its_cycle: an instance in a cycle through its dict and through a self-referencing list, and a plain Python subclass of it, held in a .NET List. Over two rounds of release and re-acquire, .NET reaches the Python ToString override while only .NET holds them, and the attributes, the cycle and the identity survive. After the list is cleared, every instance is freed (checked with the class's refcount, since freed objects aren't GC-tracked).
  • test_namespaced_subclass_cycle_is_collected: 300 unreferenced instances in self-cycles and pair cycles are freed. In a pair .NET holds one side of, the other side's attributes stay reachable, and both are freed once .NET lets go.
  • test_namespaced_subclass_direct_del_call_keeps_net_object: a direct __del__() call doesn't release the .NET object.
  • test_namespaced_subclass_held_by_net_keeps_its_wrapper[in_cycle]: with and without a cycle, the object returned from .NET still converts back to .NET (List.Contains, GetType()) after a .NET GC.
  • test_namespaced_subclass_resurrected_by_python_keeps_net_object: an instance dropped in a cycle whose other member's __del__ appends it to a list keeps its .NET object, both right after .NET's GC and after the finalized object is handled. The previous version of this change failed it with TypeError: Invoked a non-static method with an invalid instance.
  • test_namespaced_subclass_resurrected_by_python_is_collected: that instance keeps its cycle, and it's freed once the list is cleared.
  • test_namespaced_subclass_resurrected_by_python_and_passed_to_net: that instance is passed through a .NET List before the finalized .NET object is handled; it keeps its attributes after Python lets go of it while the list holds it, and it's freed once the list is cleared. The previous version of this change crashed on it.
  • test_namespaced_subclass_taken_back_by_python_then_released: an instance .NET held in a cycle is taken back by Python, then released by Python and .NET, and it's freed.
  • test_namespaced_subclass_runs_base_finalizer_once[none|self|resurrected]: a subclass of Python.Test.FinalizedConstructorTest runs its base finalizer once, without a cycle, in a self-cycle, and after Python gets it back through __del__. The previous version of this change counted 2 for the last two.

On master, the first five fail. With each part of the change removed in turn, at least one fails: without clearing the finalized flag, the second round loses the attributes; without the __del__ guard, TypeError: Invoked a non-static method with an invalid instance; without the wrapper table, a segmentation fault; without the tp_dealloc free, the refcount checks fail (leak); without the Finalize branch, a cycle's attributes are lost. Without the resurrection-tracking handle, TypeError: Invoked a non-static method with an invalid instance. Without deferring the base finalizer, a segmentation fault and a finalizer count of 2. Without re-registering the .NET object, without giving it back to Python, or without the tp_finalize check that frees a cycle .NET already let go of, the refcount checks fail. Treating every deferred object as still referenced by Python fails the taken-back test (leak). If ToPython doesn't clear that check, the passed-to-.NET test loses the attributes. Recording that ToPython took the reference back only matters when it races .NET's finalizer, which no test can trigger deterministically. On Python 3.7, with the 3.8 flag location or without Py_TPFLAGS_HAVE_FINALIZE, three tests lose the attributes.

The CI steps, Python 3.11 / .NET 10:

  • dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skipped
  • dotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passed
  • pytest --runtime netcore tests: 500 passed, 23 skipped
  • dotnet test src/python_tests_runner/: 2 passed

pytest --runtime netcore tests/test_subclass.py also passes, 25 tests, on Python 3.7.16, 3.8.20, 3.12.16, 3.13.18 and 3.14.10, and pytest --runtime netcore tests passes on 3.7.16 (500 passed, 23 skipped). On 3.7.16, the issue's reproduction prints 7.

Also tested end to end in a Lean Python backtest. An algorithm holds the instance above (cycle through its dict and a self-referencing list) in a .NET List, releases it over two rounds, and checks the attributes and the ToString override reached from .NET. It also creates 100 unreferenced instances, clears the list, and checks that no instance is left. It also drops an instance in a cycle whose other member's __del__ gives it back to Python, calls GetHashCode() on it before and after the finalized .NET object is handled, then checks that such an instance is freed once released. Last, it passes such an instance through a .NET List before the finalized .NET object is handled, lets go of it in Python, and checks its attributes from the list. With this change it logged code=7 in both rounds, 0 instances left, resurrected by Python: code=7 type=Resurrected, 0 resurrected instances left, passed to .NET after Python got it back, then released by Python: code=7 and 0 such instances left. Without it, the backtest failed with 'CycleHolder' object has no attribute 'code', as the issue describes.

@quantconnect-kronos quantconnect-kronos Bot added kronos:develop:working develop: in progress kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 23, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 23, 2026 16:52

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Labeled risk:high: the fix sets and clears a bit in CPython's private GC header (_gc_prev), and changes how long every __namespace__ subclass instance's Python object and wrapper stay alive. CI on 3.8–3.14 and the Lean jobs back the bit layout, but a person should still sign off before merging.

What I checked on this head:

  • The issue's reproduction now keeps the attributes, and the 5 new tests fail on master and pass here (18/18 in tests/test_subclass.py).
  • I added a case beyond the tests: a plain Python subclass of a __namespace__ class is first released by .NET without a cycle, then comes back, gets a cycle, and is released again. I expected trouble because subtype_dealloc sets the finalized flag after tp_finalize, so the flag could stay set and stop the GC from calling it the second time. It keeps its attributes here. On master it loses them.
  • Locking: KeptByManagedObject/ReleasedByManagedObject are only touched under the GIL. PythonDerivedType.Finalize runs from Finalizer.Collect's derived queue, not on the .NET finalizer thread.

One cost, not blocking: the ConditionalWeakTable update in ReplaceGCHandle runs every time a __namespace__ object's Python references come and go. In a local microbenchmark, a .NET→Python round trip (x = held[i]; del x) went from ~1.1 µs to ~1.5 µs. A .NET call into a Python override on an object only .NET holds went from ~1.6 µs to ~1.78 µs. Lean itself doesn't define __namespace__ classes, so only user code that does pays this.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:high High risk and removed kronos:review:working review: in progress labels Nov 23, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 23, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested for two cases:

  • An ordinary Python object's __del__ can resurrect the namespaced instance without going through ToPython. The new weak handle then lets .NET collect its managed instance while Python still references it. GetHashCode() raises TypeError: Invoked a non-static method with an invalid instance; master succeeds. Preserve ownership for that resurrection path and add regression coverage.
  • The fix still loses the attributes on supported Python 3.7. Its finalized bit is in gc_refs, not the word immediately before the object. Use the correct layout and test that supported version.

Verification: Python 3.11 / .NET 10: 491 Python tests passed, 23 skipped; embedding tests 1047 passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. Tested end to end: the original cycle survives both release/reacquire rounds and leaves 0 instances after release. The added Python-resurrection case fails on this change and passes on the base runtime. On CPython 3.7.12, the issue's managed-held self-cycle still raises AttributeError. Reproductions and locations are inline.

Risk: risk:high, because the ownership change can invalidate an instance that remains reachable from Python, and preservation is not verified across the full supported ABI range.

After package release, Lean's pinned pythonnet references need updating.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
Comment thread src/runtime/Types/ClassDerived.cs Resolved
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 23, 2026
quantconnect-kronos Bot and others added 2 commits November 23, 2026 17:23
… cycle

The cyclic GC can't see .NET's reference to a __namespace__ subclass
instance, so it cleared the instance's cycle, its __dict__ included, while
.NET still held the object. The type's tp_finalize now hands the object
to its .NET object instead: the .NET object keeps one reference to it, and
the Python object holds the .NET object weakly. Python takes that
reference back when the object returns to Python, and the .NET object
releases it when it's finalized, after which Python frees the cycle.

The wrapper a Python object holds weakly is now kept alive as long as its
.NET object, so the object still converts back to .NET after a .NET GC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts, and support Python 3.7

When another object's __del__ gave Python back an instance the cycle GC had handed to .NET, its
.NET object could be collected while Python still used it. The finalized .NET object now stays
reachable until the queued finalization runs, which gives the Python object a strong handle to it
again when Python still references it.

On Python 3.7, the GC's finalized flag is in gc_refs, and tp_finalize only runs for types with
Py_TPFLAGS_HAVE_FINALIZE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@quantconnect-kronos
quantconnect-kronos Bot force-pushed the kronos/bug-169-namespace-subclass-cycle-attributes branch from c442c5f to 8482a4d Compare November 23, 2026 17:40
@quantconnect-kronos
quantconnect-kronos Bot marked this pull request as draft November 23, 2026 17:42
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 23, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 23, 2026 18:21

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving 8482a4d. Both findings from the earlier changes-requested review are resolved:

  • An object Python resurrects through another object's __del__: the reviewer's reproduction is now a test, and it passes. I added a case where Python resurrects the object while a .NET List also holds it. .NET's call into the ToString override, is identity and the attributes survive both release rounds, and the class's refcount returns to its starting value once both let go. Master loses the attributes.
  • Python 3.7: on 3.7.16, tests/test_subclass.py passes 20/20. Without HaveFinalize, 3 tests fail. The offset matches the 3.7 PyGC_Head layout: gc_refs is at ob - 16 on 64-bit Linux, and at ob - 8 where long double is 8 bytes.

This also fixes a crash on master. When .NET holds an object in the issue's self-cycle and calls a Python override that reads a lost attribute, the override raises. Releasing the object after that segfaults on master. Here, the override returns its value.

A separate crash happens on master and on this head: a .NET call into an override that raises, followed by releasing the object, intermittently segfaults with no cycle. It's tracked in #179 and doesn't block this change.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 23, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 23, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The earlier managed-ownership finding remains in the resurrection approach:

  • Queued cleanup frees a live object. After Python resurrects an instance through another object's __del__, passing it through a .NET List before queued finalization is processed transfers ownership in ToPython. The existing queued Finalize then clears and frees it despite Python and .NET still holding it. The instance loses code; the identical reproduction succeeds on master. This also fails end to end.
  • Managed base finalizers run twice. One unreachable self-cyclic subclass of Python.Test.FinalizedConstructorTest increments its finalization counter twice on this head, versus once on master and once without the cycle. Re-registering the whole managed object repeats user/base finalizer side effects.

These share the same lifetime cause: bridge-reference cleanup must be separated from managed resource finalization, not handled by resurrecting and re-registering an already-finalized managed object. Add regression coverage for both transitions. Details are inline.

The Python 3.7 finding is resolved: all 20 subclass tests pass on 3.7.16. Local Python 3.11 verification: 495 Python tests passed, 23 skipped; 1049 embedding tests passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. Those suites do not catch the cases above.

risk:high: the new evidence includes freeing a still-live wrapper and repeating managed finalizer side effects.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 23, 2026
….NET gets it back

Deferring the .NET finalization of an object Python may still reference,
instead of re-registering an already finalized object, runs the base type's
finalizer once. The finalizer decides atomically whether the cleanup is
deferred, so .NET getting the object back before the queued cleanup runs
no longer frees a live object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@quantconnect-kronos

Copy link
Copy Markdown
Author

Both findings from the changes-requested review are fixed in 598f456; see the inline reply. The new tests, results and limits are in the description.

@quantconnect-kronos
quantconnect-kronos Bot marked this pull request as draft November 23, 2026 19:20
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 23, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 23, 2026 19:44

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving 598f456. It resolves both findings from the last changes-requested review:

  • Base finalizer runs once. When finalization is deferred, the generated Finalize now skips the base finalizer, so it runs only on the final pass. A subclass of FinalizedConstructorTest counts 1 in each of these cases: a self-cycle, an object .NET held in a cycle that Python then takes back, passes to .NET again and releases, and 200 instances in cycles held by .NET over 4 rounds of release and re-acquire. The class refcount also returns to where it started. On master, I also get 1 for the plain self-cycle, so that case isn't a regression either way.
  • Queued cleanup no longer frees a live object. ToPython, tp_finalize and the .NET finalizer now update shared state under one lock, so cleanup that's already queued sees the take-back. The test covering this passes.

I also ran a .NET thread that calls GC.Collect() in a loop while Python made 300 rounds of cycles and took objects back from a List. The attributes and the ToString override held, with no crash over 8 repeated runs. On master, this stress test loses the attributes. Locally on Python 3.11 / .NET 10, pytest --runtime netcore tests gives 500 passed and 23 skipped.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 23, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 23, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The previous queued-readback and repeated-base-finalizer reproductions now pass, but the ownership protocol still has two blocking transitions:

  • Inbound handoff without readback loses Python state. A Python-resurrected instance added to a .NET List loses code after Python releases it, although the list still holds it. The new test's alias = held[0] masks this by clearing ReturnedToPython. This remains the preservation required by #169, not a new regression against master. Reproduced locally and tested end to end.
  • Rejected deferral permanently suppresses managed cleanup. When Finalizer.Instance.Enable is false, enqueueing is rejected but PyFinalize still skips the base finalizer. The resource-owning base finalizes 0 times on this head, including after re-enabling and collecting again, versus 1 on master.

Local Python 3.11 / .NET 10 verification: 500 Python tests passed, 23 skipped; 1047 embedding tests passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. The additional inbound-handoff test fails with AttributeError. risk:high: the remaining transitions lose state of a managed-held instance and suppress resource cleanup.

@Martin-Molinero Decision needed: complete the current ownership/deferral protocol, or replace its coupling of bridge cleanup to managed finalization before proceeding? These are further failures of the same lifetime cause, not requests for another resurrection special case.

  • A. Complete ownership accounting (recommended): retain the approach, account for Python-to-.NET transfers as well as readbacks, and guarantee cleanup when deferral is rejected. This is the smaller extension, but needs regression coverage for both transitions and an end-to-end preservation check without readback.
  • B. Separate the lifetime mechanisms: replace the protocol so Python-cycle preservation and once-only managed resource finalization do not depend on the same resurrection markers. More rework; the same preservation and cleanup tests must pass.

Please choose the approach, or another way to meet those invariants.

// .NET already let go of the object while Python still referenced it: the GC frees the cycle
lock (KeptLock)
{
if (ReturnedToPython.Remove(ob.DangerousGetAddress()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The historical return marker is not current managed ownership. DeferFinalization records ReturnedToPython, but only .NET-to-Python ToPython removes it. Passing a Python-resurrected instance into a .NET List through held.Add(survivors[0]) does not. Once Python releases the survivor, this branch lets cyclic GC clear its dict while the .NET list still holds the object.

Minimal reproduction using the committed test: in test_namespaced_subclass_resurrected_by_python_and_passed_to_net, remove alias = held[0], the identity assertion, the later alias.code assertion and del alias; keep held.Add, queue draining and survivors.clear(). Its later held[0].code == 7 assertion then raises AttributeError on this head. I reproduced that exact no-readback path in a standalone test and end to end; the readback variant succeeds.

This is the same managed-held state-preservation invariant requested by #169. The inbound ownership transfer must not require an otherwise unnecessary readback to preserve the instance. See the approach decision in the review body.

if (ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference))
{
Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference);
return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skip the base finalizer only when deferral actually exists. AddDerivedFinalizedObject returns without queueing when Finalizer.Instance.Enable is false, but this branch still returns false. The generated finalizer therefore skips the managed base, with no queued object to retain or re-register it. Re-enabling does not recover cleanup.

With the test fixture loaded, this reproduction gives base-finalizer counts 0 then 0 on this head, versus 1 then 1 on master, in two fresh-process comparisons with the loaded runtime verified:

import gc
from Python.Test import FinalizedConstructorTest
from Python.Runtime import Finalizer
from System import GC, Object
from System.Collections.Generic import List

class Derived(FinalizedConstructorTest):
    __namespace__ = 'Synthetic.DisabledBridge'
    def __init__(self):
        self.me = self

Finalizer.Instance.Threshold = 10000000
before = FinalizedConstructorTest.Finalized
held = List[Object]()
held.Add(Derived())
gc.collect()
instance = held[0]
instance.me = None
del instance
Finalizer.Instance.Enable = False
held.Clear()
for _ in range(3):
    GC.Collect()
    GC.WaitForPendingFinalizers()
print(FinalizedConstructorTest.Finalized - before)
Finalizer.Instance.Enable = True
for _ in range(6):
    gc.collect()
    GC.Collect()
    GC.WaitForPendingFinalizers()
    Finalizer.Instance.Threshold = 1
    List[Object]([object()])
    Finalizer.Instance.Threshold = 10000000
print(FinalizedConstructorTest.Finalized - before)

Disabling Python-reference finalization must not permanently disable the managed base's resource finalization. Cover the rejected-enqueue transition as part of the lifetime protocol.

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 23, 2026
@quantconnect-kronos

Copy link
Copy Markdown
Author

Both findings from the latest review reproduce on 598f456: the no-readback List case raises AttributeError, and the disabled-finalizer case counts 0 and 0. I'm holding further changes until the approach question above is answered.

For option A, the change would be:

  • Clear the resurrection mark when Python passes the object to .NET, as ToPython already does in the other direction. Python then keeps the object, and .NET's finalizer decides again.
  • Defer the base finalizer only when the cleanup was actually queued. With Finalizer.Instance.Enable false, it runs at once as on master.

Each comes with a regression test.

@quantconnect-kronos quantconnect-kronos Bot added kronos:develop:idle develop: paused and removed kronos:develop:working develop: in progress labels Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kronos:develop:idle develop: paused risk:high High risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

__namespace__ subclass held by .NET loses its Python attributes when it is part of a reference cycle

0 participants